<template>
  <Card style="width:100%" class="detail-content-layout mb16">
    <template #title>
      {{ $t('转固') }}
    </template>
    <template #extra>
      <Icon @click="printPreviewPdf('CAP',info)" style="font-size: 19px; margin-right: 10px;" type="ios-print" />
      <div class="h-arrow-wrap" @click="toggle = !toggle">
        <i :class="{toggleActive:toggle}" class="iconfont zy-common-jiantou h-arrow-icon"></i>
      </div>
    </template>
    <transition name="slide-up">
      <div v-if="toggle">
        <Form ref="form" :model="form" :rules="rules" label-position="top">
          <Row :gutter="24">
            <!--            <Col span="6">-->
            <!--              <FormItem :label="$t('资产编号')" prop="assetNo">-->
            <!--                <Input :disabled="disabled" clearable type="text" v-model="form.assetNo" :placeholder="$t('请输入')" />-->

            <!--              </FormItem>-->
            <!--            </Col>-->
            <Col span="6">
              <FormItem :label="$t('部门')">
                <Input maxlength="100" disabled clearable type="text" v-model="form.department" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('成本中心')">
                <Input maxlength="100" :disabled="disabled" clearable type="text" v-model="form.costCenter"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('已安装/使用的资产的位置')">
                <Input maxlength="100" :disabled="disabled" clearable type="text" v-model="form.locationOfAssetsInstalled"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem maxlength="100" :label="$t('资产编号')">
                <Input disabled clearable type="text" v-model="form.assetNo" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('品牌')">
                <Input maxlength="100" :disabled="disabled" clearable type="text" v-model="form.brand" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('型号')">
                <Input  maxlength="100" :disabled="disabled" clearable type="text" v-model="form.model" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('其他')">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.others"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('类别')" prop="cagegory">
                <Select
                    transfer
                    v-model="form.cagegory"
                    clearable
                    :disabled="disabled"
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option
                      v-for="(item, index) of capCagegory"
                      :value="item.label"
                      :key="index"
                      :label="item.label"
                  />
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('收购方式')" prop="acquisitionMethodCCD">
                <Select
                    transfer
                    v-model="form.acquisitionMethodCCD"
                    clearable
                    :disabled="disabled"
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option
                      v-for="(item, index) of capAcquisitionMethod"
                      :value="item.label"
                      :key="index"
                      :label="item.label"
                  />
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('如果选择其他方式，收购方式')" prop="acquisitionMethodIfOtherIsSelected" :required="form.acquisitionMethodCCD==='Other'">
                <Input maxlength="100" :disabled="disabled" clearable type="text" v-model="form.acquisitionMethodIfOtherIsSelected"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('附件1')" prop="appendix">
                <Select
                    transfer
                    v-model="form.appendix"
                    clearable
                    :disabled="disabled"
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option
                      v-for="(item, index) of capAppendix"
                      :value="item.label"
                      :key="index"
                      :label="item.label"
                  />
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('验收日期')" prop="dateOfAcceptance" required>
                <DatePicker :disabled="disabled" v-model="form.dateOfAcceptance" type="date"
                            :placeholder="$t('请选择')"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('结语') " prop="concluison">
                <Select
                    transfer
                    v-model="form.concluison"
                    clearable
                    :disabled="disabled"
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option
                      v-for="(item, index) of capConcluison"
                      :value="item.label"
                      :key="index"
                      :label="item.label"
                  />
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('验收人员')" prop="acceptancePersonnel">
                <Select
                    transfer
                    v-if="!disabled"
                    :disabled="disabled"
                    v-model="form.acceptancePersonnel"
                    filterable
                    multiple
                    clearable
                    :remote-method="searchUserList"
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in userList" :key="index" :value="item.id"
                          :label="item.realname"></Option>
                </Select>

                <Select
                    transfer
                    v-else
                    v-model="form.acceptancePersonnel"
                    multiple
                    disabled
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in userNameList" :key="index" :value="item.id"
                          :label="item.realname"></Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('提交人')" v-if="disabled">
                <Input disabled clearable type="text" v-model="form.submitByStr" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <!--            <Col span="6">-->
            <!--              <FormItem :label="$t('备注')">-->
            <!--                <Input :disabled="disabled" clearable type="text" v-model="form.remark"-->
            <!--                       :placeholder="$t('请输入')"></Input>-->
            <!--              </FormItem>-->
            <!--            </Col>-->

            <Col span="6" v-if="disabled">
              <FormItem :label="$t('提交时间')">
                <Input disabled clearable type="text" v-model="form.submitTime" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem :label="$t('接受资产的描述')">
                <Input maxlength="4000" :disabled="disabled" clearable type="textarea" v-model="form.descriptionOfAssetAcceptance"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6" class="autoHeight">
              <FormItem :label="$t('SAP中的固定资产截图')" prop="assetNos">
                <uploadFile accept=".jpg,.jpeg,.png,.gif,bmp" key="12345" :fileList="info.assetNos" :disabled="disabled"
                            @change="(list)=>{form.assetNos = list}"/>
              </FormItem>
            </Col>

          </Row>
        </Form>
        <div class="tableContent mb16">
          <p class="tax">{{$t('无税总资本')}}</p>
          <Table class="resizable-table" @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,'capitalizationTable')}" :columns="columns" :data="dataSource" border>
            <template slot-scope="{ row,index }" slot="action">
              <div class="ivu-table-cell-slot">
                <span class="operationBtn" v-if="row.operation ==='action' && !disabled" @click="addItem">{{$t('新增')}}</span>
                <span v-if="row.operation !=='action' && !disabled" class="operationBtn"
                      @click="removeItem(index)">{{$t('删除')}}</span>
                <span v-if="row.operation !=='action' && !row.edit  && (!disabled) " class="operationBtn"
                      @click="editItem(index)">{{  row.edit  ? $t('更新'):$t('编辑') }}</span>
                <span v-if="row.operation !=='action' && row.edit  &&  (!disabled)" class="operationBtn"
                      @click="saveItem(index)">{{$t('提交')}}</span>
                <span v-if="row.operation !=='action' && row.edit  &&  (!disabled)" class="operationBtn"
                      @click="cancelSaveItem(index)">{{$t('取消')}}</span>
              </div>
            </template>
            <template slot-scope="{ row,index }" slot="index">
              <p  v-if="row.operation !=='action'" style="text-align: left">{{ index + 1 }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot1">
              <Input maxlength="200" v-model.trim="dataSource[index].description" :placeholder="$t('请输入')"
                     v-if="row.operation !=='action'  && row.edit"/>
              <p style="text-align: left" v-else>{{ dataSource[index].description }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot2">
              <Input maxlength="200" v-model.trim="dataSource[index].type" :placeholder="$t('请输入')"
                     v-if="row.operation !=='action'  && row.edit"/>
              <p style="text-align: left" v-else>{{ dataSource[index].type }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot3">
              <Input maxlength="200" v-model.trim="dataSource[index].vendor" :placeholder="$t('请输入')"
                     v-if="row.operation !=='action'  && row.edit"/>
              <p style="text-align: left" v-else>{{ dataSource[index].vendor }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot4">
              <Input maxlength="200" type="number" v-model.trim="dataSource[index].quantity" :placeholder="$t('请输入')"
                     v-if="row.operation !=='action'  && row.edit"/>
              <p style="text-align: left" v-else>{{ dataSource[index].quantity }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot5">
<!--              <Input maxlength="200" type="number" v-model.trim="dataSource[index].currency" :placeholder="$t('请输入')"-->
<!--                     v-if="row.operation !=='action'  && row.edit"/>-->

              <InputNumber class="prependMoneyIcon prependIcon tableInputNumberbr" style="width: 100%" size="mini" clearable
                           max="999999999" type="number" v-model.trim="dataSource[index].currency"
                           :placeholder="$t('请输入')"
                           :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                           :parser="value => value.replace(/k\￥\s?|(,*)/g, '')"
                           v-if="row.operation !=='action'  && row.edit "/>


              <p style="text-align: left" v-else>{{ dataSource[index].currency | thousandth }}</p>
            </template>
            <template slot-scope="{ row,index }" slot="slot6">
              <p style="text-align: left;" v-if="row.operation !=='action'">{{ dataSource[index].quotationCost | thousandth}}</p>
              <p style="text-align: left;" v-else >{{ formatQuotationCost() | thousandth }}</p>
            </template>
          </Table>
        </div>
        <rejectInfo :rejectFlows="rejectFlows"/>
      </div>
    </transition>
  </Card>
</template>

<script>
import uploadFile from "@/views/devBasic/capex/components/uploadFile";
import mixins from "@/views/devBasic/capex/components/mixins";
import rejectInfo from "@/views/devBasic/capex/components/rejectInfo";
import moment from 'moment'
const totalComlums = {quotationCost: "", amount: 0, operation: "action", id: "",edit:false,vendor:""}
export default {
  name: "capitalization",
  components: {uploadFile, rejectInfo},
  mixins: [mixins],
  props: {
    info: {
      type: Object,
      default: () => {
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    approvalInfo: {
      type: Object,
      default: () => {
      }
    },
    rejectFlows: {
      type: Object,
      default: () => {
      }
    },
    expand: {
      type: Boolean,
      default: false
    },
  },
  data() {
    const validateFile = (rule, value, callback) => {
      if (!(Array.isArray(this.form.assetNos) && this.form.assetNos.length > 0)) {
        callback(new Error(this.$t('请上传附件')));
      } else {
        callback();
      }
    };
    const validateSelect = (rule, value, callback) => {
      if (!(Array.isArray(this.form.acceptancePersonnel) && this.form.acceptancePersonnel.length > 0)) {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    };
    const acquisition = (rule, value, callback) => {
      if (this.form.acquisitionMethodCCD === 'Other' && !value) {
        callback(new Error(this.$t('请输入')));
      } else {
        callback();
      }
    };
    const validateSelectDate = (rule, value, callback) => {
      if (!this.form.dateOfAcceptance) {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    };
    return {
      toggle: true,
      form: {
        department: "",
        costCenter: "",
        locationOfAssetsInstalled: "",
        assetNo: "",
        brand: "",
        model: "",
        others: "",
        cagegory: "",
        acquisitionMethodCCD: "",
        acquisitionMethodIfOtherIsSelected: "",
        appendix: "",
        dateOfAcceptance: "",
        concluison: "",
        descriptionOfAssetAcceptance: "",
        acceptancePersonnel: "",
      },
      rules: {
        assetNos: [{required: true, validator: validateFile, trigger: 'change'}],
        cagegory: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'change'}],
        acquisitionMethodCCD: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'change'}],
        appendix: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'change'}],
        dateOfAcceptance: [{message: this.$t('请输入'), trigger: 'change',validator:validateSelectDate}],
        concluison: [{required: true, type: 'string', message: this.$t('请输入'), trigger: 'change'}],
        acceptancePersonnel: [{required: true, validator: validateSelect, trigger: 'change'}],
        acquisitionMethodIfOtherIsSelected: [{trigger: 'blur', validator: acquisition}],
      },
      userList: [],
      dataSource: [{...totalComlums}],
      columns: [
        {
          title: this.$t('项目'),
          key: "processCode",
          slot: "index",
            width: 100,
            resizable:true,
            renderHeader: (h) => {
                return h('div', [
                    h('span', {
                        domProps: {
                            innerHTML: this.$t('项目')
                        },
                        attrs: {
                            class: "required "
                        }
                    }),
                ])
            }
        },
        {
          title: this.$t('描述'),
          key: "description",
          slot: "slot1",
            resizable:true,
            renderHeader: (h) => {
                return h('div', [
                    h('span', {
                        domProps: {
                            innerHTML: this.$t('描述')
                        },
                        attrs: {
                            class: "required "
                        }
                    }),
                ])
            }
        },
        {
          title: this.$t('类型'),
          key: "type",
          slot: "slot2",
            resizable:true,
            renderHeader: (h) => {
                return h('div', [
                    h('span', {
                        domProps: {
                            innerHTML: this.$t('类型')
                        },
                        attrs: {
                            class: "required "
                        }
                    }),
                ])
            }
        },
        {
          title: this.$t('供应商'),
          key: "vendor",
          slot: "slot3",
            resizable:true,
            renderHeader: (h) => {
                return h('div', [
                    h('span', {
                        domProps: {
                            innerHTML: this.$t('供应商')
                        },
                        attrs: {
                            class: "required "
                        }
                    }),
                ])
            }
        },
        {
          title: this.$t('数量'),
          key: "quantity",
          slot: "slot4",
            resizable:true,
            renderHeader: (h) => {
                return h('div', [
                    h('span', {
                        domProps: {
                            innerHTML: this.$t('数量')
                        },
                        attrs: {
                            class: "required "
                        }
                    }),
                ])
            }
        },
        {
          title: this.$t('货币'),
          key: "currency",
          slot: "slot5",
            resizable:true,
            renderHeader: (h) => {
                return h('div', [
                    h('span', {
                        domProps: {
                            innerHTML: this.$t('货币')
                        },
                        attrs: {
                            class: "required "
                        }
                    }),
                ])
            }
        },
        {
          title: this.$t('报价成本'),
          key: "quotationCost",
          slot: "slot6",
            resizable:true,
        },
        {
          title: this.$t('操作'),
          key: "Items",
          slot: "action",
          width:250,
          align:"center"
        }
      ],
      copyDataSource:[],
      userNameList:[]
    }
  },
  //
  //
  created() {
      this.getColumnWidth(this.columns,'capitalizationTable')
    this.form.submitByStr = this.userName

    if (this.info.capexCapitalizationInfoDTO && this.info.capexCapitalizationInfoDTO.id){
      this.setParams()
    }else{
      const {orgName, assetNo,cvDetails} = this.info;
      this.form.department =  this.info.cvInfo.cvDepartmentId
      this.form.assetNo = assetNo
      cvDetails.forEach((item,index)=> {
        item.processCode=index+1
        item.edit=false
      })
      this.dataSource = JSON.parse(JSON.stringify(cvDetails))
      this.dataSource.push(totalComlums)
      this.copyDataSource = JSON.parse(JSON.stringify(this.dataSource))
    }
    if (this.disabled) {
      this.toggle = false
    }
    //
    // if (!this.disabled) {
    //
    // }

    if (this.expand){
      this.toggle = true
    }
  },
  methods: {
    formatQuotationCost(){
      let total = 0
      this.dataSource.forEach(item=>{
        if (item.quantity && item.currency){
          item.quotationCost = item.quantity * item.currency
        }else{
          item.quotationCost = ""
        }
        total = total + (item.quotationCost || 0)
      })

      return total
    },
    saveItem(index) {

      this.activeIndex = index
      if (!this.dataSource[this.activeIndex].processCode) {
        this.$Message.error(this.$t('请输入'))
        return;
      }

      if (!this.dataSource[this.activeIndex].description) {
        this.$Message.error(this.$t('请输入'))
        return;
      }
      if (!this.dataSource[this.activeIndex].type) {
        this.$Message.error(this.$t('请输入'))
        return;
      }
      if (!this.dataSource[this.activeIndex].vendor) {
        this.$Message.error(this.$t('请输入'))
        return;
      }
      if (!this.dataSource[this.activeIndex].quantity) {
        this.$Message.error(this.$t('请输入'))
        return;
      }
      if (!this.dataSource[this.activeIndex].currency) {
        this.$Message.error(this.$t('请输入'))
        return;
      }
      // if (!this.dataSource[this.activeIndex].quotationCost) {
      //   this.$Message.error(this.$t('请输入'))
      //   return;
      // }


      this.dataSource[this.activeIndex]['edit'] = false
      this.$forceUpdate()
    },
    cancelSaveItem(index) {
      const obj = this.copyDataSource.find(item => {
        if (this.dataSource.find(m => m.processCode === item.processCode))
          return item
      })
      if (obj)
        this.dataSource.splice(index, 1, {...obj, edit: false})
      else
        this.dataSource.splice(index, 1)
    },
    checkEditStatus() {
      const obj = this.dataSource.find(item => item.edit)
      if (obj) {
        this.$Message.error(this.$t('请先保存'))
        return true
      } else {
        return false
      }
    },
    editItem(index) {
      if (this.checkEditStatus()) return false
      this.dataSource[index]['edit'] = true
      this.activeIndex = index
      this.copyDataSource = JSON.parse(JSON.stringify(this.dataSource))
      this.$forceUpdate()

    },
    addItem() {

      if (this.checkEditStatus()) return false
      const id = this.dataSource.length > 1 ? (this.dataSource[this.dataSource.length - 2].processCode || 0) + 1 : 1
      const obj = {
        processCode: id,
        description: "",
        type: "",
        vendor: "",
        quantity: "",
        currency: "",
        quotationCost: "",
        edit: true
      }
      this.dataSource.splice(this.dataSource.length - 1, 0, obj)
    },
    removeItem(index) {
      this.dataSource.splice(index, 1)
    },
    searchUserList(query) {
      this.axios({
        method: 'get',
        url: '/dms/user/userList',
        params: {key: query}
      }).then(res => {
        if (res.code === 200) {
          this.userList = res.data
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    setParams() {
      const {submitRemark, submitTime, submitByStr} = this.approvalInfo
      const {
        department,
        costCenter,
        locationOfAssetsInstalled,
        assetNo,
        brand,
        model,
        others,
        cagegory,
        acquisitionMethodCCD,
        acquisitionMethodIfOtherIsSelected,
        appendix,
        dateOfAcceptance,
        concluison,
        descriptionOfAssetAcceptance,
        acceptancePersonnel,
        acceptancePersonnelName
      } = this.info.capexCapitalizationInfoDTO;
      const {assetNos,capexCapitalizationDetails} = this.info;
      this.form = Object.assign(this.form, {
        remark: submitRemark,
        submitTime,
        submitByStr,
        assetNos,
        department,
        costCenter,
        locationOfAssetsInstalled,
        assetNo,
        brand,
        model,
        others,
        cagegory,
        acquisitionMethodCCD,
        acquisitionMethodIfOtherIsSelected,
        appendix,
        dateOfAcceptance: moment(dateOfAcceptance).format('YYYY-MM-DD'),
        concluison,
        descriptionOfAssetAcceptance,
        acceptancePersonnel
      })
      capexCapitalizationDetails.forEach((item,index)=> {
        item.processCode=index+1
        item.edit=false
      })

      let _participantNames = acceptancePersonnelName ? acceptancePersonnelName.split(','):[]
      let _participants = acceptancePersonnel ? acceptancePersonnel.split(','):[]
      let userList = [];
      this.form.acceptancePersonnel = [..._participants].map(item=>{
          return item/1
      })
      _participants.forEach((item, index) => {
         userList.push({
            id: item/1,
            realname: _participantNames[index]
          })

      })

      if (!this.disabled)
        this.searchUserList("")
      else
        this.userNameList = JSON.parse(JSON.stringify(userList))



      this.dataSource = JSON.parse(JSON.stringify(capexCapitalizationDetails))
      this.dataSource.push(totalComlums)
      this.dataSource.forEach(item=> item.edit = false)
      this.copyDataSource = JSON.parse(JSON.stringify(this.dataSource))
      this.$forceUpdate()
    },
    async getParams(status) {
      const valid = status?status:await this.$refs.form.validate()

      if (valid) {

        const form = JSON.parse(JSON.stringify(this.form))
        form.dateOfAcceptance = form.dateOfAcceptance ? moment(form.dateOfAcceptance).format('YYYY-MM-DD'):""
        form.acceptancePersonnel =  (form.acceptancePersonnel || []).join(',')
        let params = {
          assetNos:form.assetNos,
        }

        delete form.assetNos

        params.capexCapitalizationInfoDTO = {...form,acquisitionMethod:form.acquisitionMethodCCD};
        delete params.capexCapitalizationInfoDTO.acquisitionMethodCCD

        let list = JSON.parse(JSON.stringify(this.dataSource))
        if (Array.isArray(list) && list.length > 0)
          list.splice(list.length - 1, 1)

          if(!status){
              if (list.find(item=> item.edit)){
                  this.$Message.error(this.$t('请先保存'))
                  return ;
              }
              if (list.length < 1){
                  this.$Message.error(this.$t('最少添加一条数据'))
                  return ;
              }
          }

        return {
          ...params,
          capexCapitalizationDetails: list,
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "./style";

.tableInputNumberbr {
  border: 1px solid #dcdee2;

  /deep/ .ivu-input-number-input {
    border: none;
  }
}
</style>

